#include <QFileDialog>
#include <QFileInfo>
#include <QMessageBox>

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "progressdialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    pdlg = new ProgressDialog(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_cancelBtn_clicked()
{
    qApp->quit();
}

void MainWindow::on_xmlChooseBtn_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
                                                    tr("Open dictionary XML"), "",
                                                    tr("dictionary (monier.xml mwe.xml)"));
    ui->xmlPathEdit->setText(fileName);
    QFileInfo xmli(fileName);
    QFileInfo pathi(xmli.absolutePath());
    if(pathi.isWritable())
        ui->idxPathEdit->setText(fileName.replace(xmli.suffix(),"idx"));
}

void MainWindow::on_idxChooseBtn_clicked()
{
    QString xmlfile = ui->xmlPathEdit->text();
    QFileInfo xmli(xmlfile);
    QString indexfile = xmli.fileName().replace(xmli.suffix(),"idx");
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Index File"),
                               indexfile,
                               tr("Index (monier.idx mwe.idx)"));
    ui->idxPathEdit->setText(fileName);

}

QPair<QString, QString> MainWindow::processLine(QString line)
{
    QString key1_string = "";
    QString lnum_string = "";

    QDomDocument doc("mw");
    doc.setContent(line);
    QDomElement docElem = doc.documentElement();

    QDomNode n = docElem.firstChild();
    while(!n.isNull()) {
        QDomElement e = n.toElement(); // try to convert the node to an element.
        if(!e.isNull() && e.tagName() == "h") {
            QDomNode key1 = n.namedItem("key1");
            if(!key1.isNull())
                key1_string = key1.toElement().text();
        }
        if(!e.isNull() && e.tagName() == "tail") {
            QDomNode lnum = n.namedItem("L");
            if(!lnum.isNull()){
                    lnum_string = lnum.toElement().text();
            }
        }
        n = n.nextSibling();
    }
    QPair<QString, QString> ret;
    ret.first = key1_string;
    ret.second = lnum_string;
    return ret;
}


void MainWindow::on_genBtn_clicked()
{
    QString xmlfile = ui->xmlPathEdit->text();
    QString idxfile = ui->idxPathEdit->text();
    if((idxfile.isEmpty() || idxfile.isNull() || idxfile.size()==0)
            ||(idxfile.isEmpty() || idxfile.isNull() || idxfile.size()==0))
    {
        QMessageBox msgBox;
        msgBox.setText(QObject::tr("Please choose file path first"));
        msgBox.exec();
        return;
    }


    pdlg->show();
    pdlg->setProgress(50);
    ui->genBtn->setEnabled(false);
    ui->cancelBtn->setEnabled(false);
    genIdx(xmlfile, idxfile);
    pdlg->close();
    ui->genBtn->setEnabled(true);
    ui->cancelBtn->setEnabled(true);
    QMessageBox::information(this, "Finished","Index file generated successfully.",QMessageBox::Ok);
}

void MainWindow::genIdx(QString xmlfilename, QString idxfilename)
{
    QFile file(xmlfilename);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QFile idxfile(idxfilename);
    if (!idxfile.open(QIODevice::WriteOnly | QIODevice::Text))
        return;

    QTextStream idxout(&idxfile);

    while (!file.atEnd()) {
        qApp->processEvents();
        qint64 pos = file.pos();
        QByteArray line = file.readLine();
        QPair<QString, QString> pair = processLine(line);
        QString key = pair.first;
        QString lnum = pair.second;

        if(!key.isNull() && !key.isEmpty() && !(key=="")) {
            QString idxitem = QString("%1;%2;%3;%4;").arg(key).arg(pos).arg(line.length()).arg(lnum);
            idxout << idxitem << "\n";
        }
    }
    idxfile.close();
    file.close();
}
